import React, { Component } from "react";
import { Link } from "react-router-dom";
import {
  supacc_search,
  supacc_add,
  supacc_delete,
  supacc_change,
  supacc_export,
} from "../../api/supplier";
import { downloadFile } from "../../utils/downloadFile";
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  SearchOutlined,
  CloudDownloadOutlined,
  FileAddOutlined,
  RedoOutlined,
} from "@ant-design/icons";
import {
  message,
  Breadcrumb,
  Card,
  Table,
  Modal,
  Button,
  Switch,
  Pagination,
  Form,
  Input,
  Row,
  Col,
} from "antd";

const { Item } = Form;
const { confirm } = Modal;

export default class Supplier extends Component {
  state = {
    //请求参数
    pagenum: 1,
    pagesize: 3,
    user_name: "",
    sup_name: "",
    supList: [],
    loading: false,
    total: 0,
    addVisible: false,
  };

  //获取供应商列表数据
  getSpuList = async () => {
    const { pagenum, pagesize } = this.state;
    const paramsInfo = {
      pagenum: pagenum,
      pagesize: pagesize,
    };
    if (this.state.user_name || this.state.sup_name) {
      paramsInfo.user_name = this.state.user_name;
      paramsInfo.sup_name = this.state.sup_name;
    }
    this.setState({ loading: true });
    try {
      let { data: res } = await supacc_search(paramsInfo);
      this.setState({ loading: false });
      if (res && res.code === 200) {
        // console.log(res);
        const supList = res.data.current_page_data;
        const total = res.data.data_sum;
        this.setState({
          supList,
          total,
        });
      } else {
        message.error(res.message);
      }
    } catch (err) {
      message.error("连接失败，请检查网络");
    }
  };
  //查询
  onFinish = (values) => {
    this.setState({}, () => {
      this.setState({
        user_name: values.user_name,
        sup_name: values.sup_name,
        pagenum: 1,
        pagesize: 3,
      });
    });
    this.getSpuList();
    console.log("Success:", values);
  };
  //分页
  pagenumChange = (pagenum) => {
    this.setState({ pagenum }, () => {
      this.getSpuList();
    });
  };
  pagesizeChange = (current, pagesize) => {
    this.setState({ pagesize }, () => {
      this.getSpuList();
    });
  };
  //启用禁用
  changeStatus = async (row) => {
    row.enable = !row.enable;
    this.setState({ loading: true });
    let id = row.id;
    let enable = row.enable;
    try {
      let { data: res } = await supacc_change({ id, enable });
      console.log(res);
      this.setState({ loading: false });
      if (res && res.code === 200) {
        this.getSpuList();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    } catch (err) {
      message.error("连接失败，请检查网络");
    }
  };
  //确认删除提示
  confirmMethod = (row) => {
    //删除方法
    const deleteMethod = async (row) => {
      this.setState({ loading: true });
      try {
        let { data: res } = await supacc_delete({ id: row.id });
        this.setState({ loading: false });
        if (res && res.code === 200) {
          message.success(res.message);
          this.getSpuList();
        } else {
          message.error(res.message);
        }
      } catch (err) {
        message.error("连接失败，请检查网络");
      }
    };

    confirm({
      title: "你确定要删除吗？",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        deleteMethod(row);
      },
      onCancel() {
        message.info("已取消");
      },
    });
  };
  //展示添加弹窗
  showAdd = () => {
    this.setState({
      addVisible: true,
    });
  };
  //取消
  handleCancel = () => {
    this.setState({
      addVisible: false,
    });
  };
  //添加供应商
  addUser = () => {
    const { addform } = this;
    // console.log(addform);
    try {
      addform
        .validateFields()
        .then(async (value) => {
          //   console.log(value);
          let { data: res } = await supacc_add(value);
          if (res && res.code === 200) {
            message.success(res.message);
            this.setState({
              addVisible: false,
            });
            this.getSpuList();
          } else {
            message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } catch (err) {
      message.error("连接失败，请检查网络");
    }
  };
  //导出excel
  exportExcel = async () => {
    const { pagenum, pagesize } = this.state;
    const paramsInfo = {
      pagenum: pagenum,
      pagesize: pagesize,
    };
    if (this.state.user_name || this.state.sup_name) {
      paramsInfo.user_name = this.state.user_name;
      paramsInfo.sup_name = this.state.sup_name;
    }
    let { data: res } = await supacc_export(paramsInfo);
    if (res) {
      downloadFile(res, "供应商列表.xlsx");
      message.success("导出供应商列表成功");
    }
  };

  componentDidMount() {
    this.getSpuList();
  }
  render() {
    const { loading, supList, pagenum, pagesize, total, addVisible } =
      this.state;
    const columns = [
      {
        title: "用户名",
        dataIndex: "user_name",
        align: "center",
      },
      {
        title: "供应商名称",
        dataIndex: "sup_name",
        align: "center",
      },
      {
        title: "状态",
        dataIndex: "enable",
        align: "center",
        render: (enable, row) => {
          return (
            <Switch
              checked={enable}
              onChange={() => this.changeStatus(row)}
            ></Switch>
          );
        },
      },
      {
        title: "操作",
        fixed: "right",
        width: 100,
        align: "center",
        render: (row) => {
          return (
            <div>
              <Button
                onClick={() => this.confirmMethod(row)}
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </div>
          );
        },
      },
    ];
    return (
      <div className="supplier">
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/">Admin</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>用户管理</Breadcrumb.Item>
          <Breadcrumb.Item>供应商管理</Breadcrumb.Item>
        </Breadcrumb>

        <Card>
          <Form
            onFinish={this.onFinish}
            ref={(c) => (this.addform = c)}
            initialValues={{ remember: true }}
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
          >
            <Row gutter={20}>
              <Col span={6}>
                <Item label="用户名" name="user_name">
                  <Input />
                </Item>
              </Col>

              <Col span={6}>
                <Item label="供应商名称" name="sup_name">
                  <Input />
                </Item>
              </Col>

              <Col span={2.5}>
                <Item>
                  <Button
                    htmlType="submit"
                    type="primary"
                    icon={<SearchOutlined />}
                  >
                    查询
                  </Button>
                </Item>
              </Col>

              <Col span={2.5}>
                <Item>
                  <Button type="info" icon={<RedoOutlined />}>
                    重置
                  </Button>
                </Item>
              </Col>

              <Col span={2.5}>
                <Item>
                  <Button
                    onClick={this.showAdd}
                    type="primary"
                    icon={<FileAddOutlined />}
                  >
                    添加
                  </Button>
                </Item>
              </Col>

              <Col span={2.5}>
                <Item>
                  <Button
                    onClick={this.exportExcel}
                    type="primary"
                    icon={<CloudDownloadOutlined />}
                  >
                    导出
                  </Button>
                </Item>
              </Col>
            </Row>
          </Form>

          <Table
            rowKey="id"
            bordered
            loading={loading}
            dataSource={supList}
            columns={columns}
            pagination={false}
          />
          <Pagination
            style={{ marginTop: "25px" }}
            current={pagenum}
            total={total}
            pageSize={pagesize}
            pageSizeOptions={["1", "2", "5", "10"]}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={(pagenum) => this.pagenumChange(pagenum)}
            onShowSizeChange={(current, pagesize) =>
              this.pagesizeChange(current, pagesize)
            }
          />
          {/* 添加用户对话框 */}
          <Modal
            destroyOnClose
            title="添加用户"
            okText="确定"
            cancelText="取消"
            visible={addVisible}
            onOk={() => this.addUser()}
            onCancel={this.handleCancel}
          >
            <Form
              name="normal_login"
              className="login-form"
              ref={(c) => (this.addform = c)}
              initialValues={{ remember: true }}
              labelCol={{
                span: 6,
              }}
              wrapperCol={{
                span: 15,
              }}
            >
              <Item
                label="用户名"
                name="user_name"
                rules={[{ required: true, message: "用户名不能为空" }]}
              >
                <Input />
              </Item>
              <Item
                label="供应商名称"
                name="sup_name"
                rules={[{ required: true, message: "供应商名称不能为空" }]}
              >
                <Input />
              </Item>
            </Form>
          </Modal>
        </Card>
      </div>
    );
  }
}
